package jus.poc.prodcons.v1;

import java.util.Date;
import jus.poc.prodcons.*;

/**
 * ProdCons gère les échanges à partir des buffers. Version naive de gestion de
 * message.
 *
 * @author Nunes Thomas <nds.thomas@gmail.com>
 * @author Feng Xu <fengxu1989@gmail.com>
 */
public class ProdCons implements Tampon {

    protected int nbBuffer;
    protected Message buffers[];
    protected int enAttente;
    protected int indice;
    protected int res;

    /**
     * Constructeur
     *
     * @param nbBuffer Le nombre de buffer.
     */
    public ProdCons(int nbBuffer) {
        this.nbBuffer = nbBuffer;
        buffers = new Message[nbBuffer];
        enAttente = 0;
        indice = 0;
        res = 0;
    }

    @Override
    public int enAttente() {
        return enAttente;
    }

    @Override
    public synchronized Message get(_Consommateur conso) throws Exception,
            InterruptedException {
        Message m;
        while (enAttente == 0) {
            wait();
        }
        m = buffers[modulo((indice - enAttente), nbBuffer)];
        ((MessageX) m).setRecu(new Date());
        enAttente--;
        notifyAll();
        return m;
    }

    @Override
    public synchronized void put(_Producteur arg0, Message arg1)
            throws Exception, InterruptedException {
        while (!(enAttente < nbBuffer)) {
            wait();
        }
        ((MessageX) arg1).setDate(new Date());
        buffers[indice] = arg1;
        indice = (indice + 1) % nbBuffer;
        enAttente++;
        notifyAll();
    }

    @Override
    public int taille() {
        return nbBuffer;
    }

    private int modulo(int a, int b) {
        int result = a % b;
        if (result < 0 && b > 0) {
            result += b;
        }
        return result;
    }
}
